﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using VodafoneLiveTile.Resources;
using System.IO;
using System.Diagnostics;
using System.Threading;

using Microsoft.Phone.Notification;
using Microsoft.Phone.Tasks;
using VodafoneLiveTile.Connections;

namespace VodafoneLiveTile
{
    public partial class MainPage : PhoneApplicationPage
    {



        public int MAX_SECONDS = 60;
        public int remainingSeconds = 0;
        public Timer timer;
        public static List<Counter> counters;
        public static List<ToastViewModel> toasts;
        public static List<Ads> ads;
        public static Account currentAccount = new Account();
        public VodafoneResult result = new VodafoneResult();
        public BasicConnection connection = null;
        bool working = false;
        bool checking = false;

        HttpNotificationChannel pushChannel;

        // The name of our push channel.
        string channelName = Config.channelName;

        public MainPage()
        {
            /// Holds the push channel that is created or found.

            PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            InitializeComponent();
            DataContext = App.ViewModel;
            Ads_List.DataContext = App.ViewModel;
            Toasts_List.DataContext = App.ViewModel;
            try
            {
                var occ = Storage.LoadUtilizations() + 1;
                new Thread(new ThreadStart(() =>
                {
                    Storage.getHTML(Storage.GetUtilizationUrl(occ, App.isTrial()),
                        (s) =>
                        {
                            Storage.DeleteUtilizations();
                        },
                        () =>
                        {
                            Storage.SaveUtilizations(occ);
                        });
                })).Start();
            }
            catch { }

            counters = Storage.LoadCounters();
            toasts = Storage.LoadToasts();

            App.ViewModel.Toasts.Clear();
            for (int i = 0; i < toasts.Count; i++)
                App.ViewModel.Toasts.Add(toasts[i]);

            ads = Storage.LoadAds();
            App.ViewModel.Ads.Clear();
            for (int i = 0; i < ads.Count; i++)
                App.ViewModel.Ads.Add(new AdsViewModel()
                {
                    ID = ads[i].ID,
                    Description = ads[i].Description,
                    ImageUri = new Uri(ads[i].ImageUrl, UriKind.RelativeOrAbsolute),
                    Name = ads[i].Name
                }
                    );
            currentAccount = Storage.LoadAccount();
            UpdateCounters();
            UpdateToasts();
            UpdateAds();

            if (counters.Count == 0)
            {
                Config.LoadDefaultCounter(counters);

                Storage.SaveCounters(counters);
            }



            SetElements();

            BuildApplicationBar(currentAccount != null && currentAccount.isActive());

            OpenChannels();
            if (currentAccount != null && currentAccount.isActive())
                SendAccountData(true);

            if (currentAccount.autoUpdate && currentAccount.isActive())
                BeginUpdate();

            checking = false;

            if (App.isTrial())
            {
                //SuggestCounter_Button.Content = Strings.BuyComplete;
                BuyComplete_Button.Visibility = System.Windows.Visibility.Visible;
            }

            if (Storage.IsFirstOpening())
            {
                MessageBox.Show(Strings.Disclaimer_Once);
                Storage.SetAlreadyOpened();
            }

        }

        public void BuildApplicationBar(bool completed)
        {
            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton credits = new ApplicationBarIconButton() { Text = Strings.Credits, IsEnabled = true };
            if (App.CurrentTheme == App.Theme.Dark)
                credits.IconUri = new Uri("\\Images\\dark\\appbar.questionmark.rest.png", UriKind.Relative);
            else
                credits.IconUri = new Uri("\\Images\\light\\appbar.questionmark.rest.png", UriKind.Relative);
            credits.Click += OpenCredits_Button_Click;
            ApplicationBar.Buttons.Add(credits);
            if (currentAccount.number != "")
            {
                ApplicationBarIconButton save = new ApplicationBarIconButton() { Text = Strings.Save, IsEnabled = true };
                if (App.CurrentTheme == App.Theme.Dark)
                    save.IconUri = new Uri("\\Images\\dark\\appbar.save.rest.png", UriKind.Relative);
                else
                    save.IconUri = new Uri("\\Images\\light\\appbar.save.rest.png", UriKind.Relative);
                save.Click += Save_Button_Click;
                ApplicationBar.Buttons.Add(save);
            }
            if (completed)
            {
                ApplicationBarIconButton delete = new ApplicationBarIconButton() { Text = Strings.Delete, IsEnabled = true };
                if (App.CurrentTheme == App.Theme.Dark)
                    delete.IconUri = new Uri("\\Images\\dark\\appbar.delete.rest.png", UriKind.Relative);
                else
                    delete.IconUri = new Uri("\\Images\\light\\appbar.delete.rest.png", UriKind.Relative);
                delete.Click += Delete_Button_Click;
                ApplicationBar.Buttons.Add(delete);

                ApplicationBarIconButton update = new ApplicationBarIconButton() { Text = Strings.UpdateLiveTile, IsEnabled = true };
                if (App.CurrentTheme == App.Theme.Dark)
                    update.IconUri = new Uri("\\Images\\dark\\appbar.update.rest.png", UriKind.Relative);
                else
                    update.IconUri = new Uri("\\Images\\light\\appbar.update.rest.png", UriKind.Relative);
                update.Click += Update_Button_Click;
                ApplicationBar.Buttons.Add(update);
            }
        }

        public void UpdateCounters()
        {

            try
            {

                Storage.getHTML(Config.get_updateCountersUrl(currentAccount.isBusiness),
                    (s) =>
                    {
                        CountersParser parser = new CountersParser(s);
                        var newList = parser.getCounters();
                        if (newList.Count <= 0)
                            return;
                        counters = newList;
                        Dispatcher.BeginInvoke(() =>
                        {
                            Storage.SaveCounters(counters);
                            App.ViewModel.Counters.Clear();
                            for (int i = 0; i < counters.Count; i++)
                                App.ViewModel.Counters.Add(new CountersViewModel()
                                {
                                    Index = counters[i].Id,
                                    Name = counters[i].Name
                                });
                        });
                    },
                    () =>
                    {

                    });

            }
            catch { }
        }
        public void UpdateToasts()
        {

            try
            {


                Storage.getHTML(Config.get_updateToastsUrl(currentAccount.isBusiness),
                    s =>
                    {
                        ToastsParser parser = new ToastsParser(s);
                        var newList = parser.getCounters();
                        if (newList.Count <= 0)
                            return;
                        toasts = newList;
                        Dispatcher.BeginInvoke(() =>
                        {
                            Storage.SaveToasts(toasts);
                            App.ViewModel.Toasts.Clear();
                            for (int i = 0; i < toasts.Count; i++)
                                App.ViewModel.Toasts.Add(toasts[i]);
                        });
                    },
                    () =>
                    {

                    });

            }
            catch { }
        }
        public void UpdateAds()
        {

            try
            {

                var url = Config.updateAdsUrl + "?name=" + Strings.Title + "&lang=" + Strings.Lang;
                Storage.getHTML(url,
                    s =>
                    {
                        AdsParser parser = new AdsParser(s);
                        var newList = parser.getAds();
                        if (newList.Count <= 0)
                            return;
                        ads = newList;
                        Dispatcher.BeginInvoke(() =>
                        {
                            Storage.SaveAds(ads);
                            App.ViewModel.Ads.Clear();
                            for (int i = 0; i < ads.Count; i++)
                                App.ViewModel.Ads.Add(new AdsViewModel()
                                {
                                    ID = ads[i].ID,
                                    Description = ads[i].Description,
                                    ImageUri = new Uri(ads[i].ImageUrl, UriKind.RelativeOrAbsolute),
                                    Name = ads[i].Name
                                });
                        });
                    },
                    () =>
                    {

                    });

            }
            catch { }
        }

        public void OpenChannels()
        {



            pushChannel = HttpNotificationChannel.Find(channelName);

            // If the channel was not found, then create a new connection to the push service.
            if (pushChannel == null)
            {
                pushChannel = new HttpNotificationChannel(channelName);

                // Register for all the events before attempting to open the channel.
                pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
                var tileUri = "http://fboscari.altervista.org/";// +currentAccount.username + "_" + currentAccount.number + "/LiveTile.png";
                try
                {
                    pushChannel.Open();

                    // Bind this new channel for Tile events.

                    pushChannel.BindToShellTile(new System.Collections.ObjectModel.Collection<Uri>()
                    {
                        new Uri(tileUri, UriKind.RelativeOrAbsolute)
                    });

                    pushChannel.BindToShellToast();
                }
                catch (InvalidOperationException e)
                {
                    e.ToString();
                    pushChannel.Close();
                }

            }
            else
            {
                // The channel was already open, so just register for all the events.
                try
                {
                    pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
                    pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);

                    // Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                    System.Diagnostics.Debug.WriteLine(pushChannel.ChannelUri.ToString());
                    //MessageBox.Show(String.Format("Channel Uri is {0}", pushChannel.ChannelUri.ToString()));


                    currentAccount.tileUri = pushChannel.ChannelUri.ToString();
                    //pushChannel.Close();
                }
                catch (InvalidOperationException ex)
                {
                    ex.ToString();
                    Dispatcher.BeginInvoke(() => MessageBox.Show(Strings.ChannelsError));
                }

            }

        }

        void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {

            Dispatcher.BeginInvoke(() =>
            {
                // Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
                System.Diagnostics.Debug.WriteLine(e.ChannelUri.ToString());
                //MessageBox.Show(String.Format("Channel Uri is {0}", e.ChannelUri.ToString()));

                Account currentAccount = Storage.LoadAccount();
                if (currentAccount.isActive())
                {
                    currentAccount.tileUri = e.ChannelUri.ToString();
                    SendAccountData(true);
                    Thread.Sleep(2000);
                }

            });
        }

        void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
            // Error handling logic for your particular application would be here.
            Dispatcher.BeginInvoke(() =>
                MessageBox.Show(String.Format("A push notification {0} error occurred.  {1} ({2}) {3}",
                    e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
                    );
        }

        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }

        private void Save_Button_Click(object sender, EventArgs e)
        {
            //if (!currentAccount.isActive())
            //    return;
            if (pushChannel == null)
                OpenChannels();
            else
                currentAccount.tileUri = pushChannel.ChannelUri.ToString();
            Storage.SaveAccount(currentAccount);
            SendAccountData(false);
            //MessageBox.Show(Strings.Saved);
        }

        private void Update_Button_Click(object sender, EventArgs e)
        {
            if (!currentAccount.Equals(Storage.LoadAccount()))
            {    //if (MessageBox.Show(Strings.SaveAccount, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                //{
                SendAccountData(true);
                Storage.SaveAccount(currentAccount);
                //}
            }
            if (currentAccount.enableLiveTile == false)
            {
                MessageBox.Show(Strings.LiveTileDisabled);
                return;
            }
            UpdateCounters();
            BeginUpdate();
        }

        private void Delete_Button_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Strings.ConfirmDelete, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            currentAccount.enableLiveTile = false;
            SendAccountData(true);

            Storage.DeleteAccount();
            currentAccount = new Account();
            SetElements();
            BuildApplicationBar(false);
            MessageBox.Show(Strings.Deleted);
        }
        public void SetElements()
        {
            ApplicationBar.IsVisible = true;
            //PageTitle.Text = Strings.Title;
            Username_Text.Visibility = System.Windows.Visibility.Visible;
            Username_Area.Visibility = System.Windows.Visibility.Visible;
            Password_Text.Visibility = System.Windows.Visibility.Visible;
            Password_Area.Visibility = System.Windows.Visibility.Visible;
            CheckUserPassword_Button.Visibility = System.Windows.Visibility.Visible;

            CancelUpdate_Button.Visibility = System.Windows.Visibility.Collapsed;
            //Current_Step_Label.Visibility = System.Windows.Visibility.Collapsed;
            RemainingTime_Label.Visibility = System.Windows.Visibility.Collapsed;
            if (!checking)
            {
                Username_Area.Text = currentAccount.username;
                Password_Area.Password = currentAccount.password;
            }
            if (currentAccount.username != "" && currentAccount.password != "")
            {
                CreateAccount_Button.Visibility = System.Windows.Visibility.Collapsed;
                LiveTile_Switch.Visibility = System.Windows.Visibility.Visible;
                Toast_Switch.Visibility = System.Windows.Visibility.Visible;
                UpdateOnStart_Switch.Visibility = System.Windows.Visibility.Visible;

                NumberChooser_Area.Visibility = System.Windows.Visibility.Visible;
                NumberChooser_Border.Visibility = System.Windows.Visibility.Visible;
                NumberChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Visible;
                NumberChooser_Label.Visibility = System.Windows.Visibility.Visible;

                //ContractChooser_Area.Visibility = System.Windows.Visibility.Visible;
                //ContractChooser_Border.Visibility = System.Windows.Visibility.Visible;
                //ContractChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Visible;
                CounterChooser_Button.Visibility = System.Windows.Visibility.Visible;
                ContractChooser_Label.Visibility = System.Windows.Visibility.Visible;
                SuggestCounter_Button.Visibility = System.Windows.Visibility.Visible;

                Show_Date_Switch.Visibility = System.Windows.Visibility.Visible;


                ApplicationBar.IsVisible = true;


                LiveTile_Switch.IsChecked = currentAccount.enableLiveTile;
                Toast_Switch.IsChecked = currentAccount.enableToast;
                UpdateOnStart_Switch.IsChecked = currentAccount.autoUpdate;

                Show_Date_Switch.IsChecked = currentAccount.showDate;

                NumberChooser_Area.Text = currentAccount.number;
                NumberChooser_Border_ContextMenu.Items.Clear();
                for (int i = 0; i < currentAccount.othersNumbers.Count; i++)
                {
                    var b = new MenuItem() { Header = currentAccount.othersNumbers[i] };
                    b.Click += NumberChooser_Click;
                    NumberChooser_Border_ContextMenu.Items.Add(b);
                }
                if (currentAccount.counter > counters.Count || currentAccount.counter < 1)
                    currentAccount.counter = 2;
                CounterChooser_Button.Content = counters[currentAccount.counter - 1].Name;//Utils.GetTypeDesc(currentAccount.counter);
                //if(currentAccount.contract== VodafoneContractType.Undefined)
                //    ContractChooser_Area.Text = Utils.GetTypeDesc(VodafoneContractType.OnlyCredit);
                //ContractChooser_Border_ContextMenu.Items.Clear();
                for (int i = 0; i < counters.Count; i++)
                {
                    //var b = new MenuItem() { Header = counters[i].Name };
                    //b.Click += ContractChooser_Click;
                    //ContractChooser_Border_ContextMenu.Items.Add(b);
                }

            }
            else
            {

                LiveTile_Switch.Visibility = System.Windows.Visibility.Collapsed;
                Toast_Switch.Visibility = System.Windows.Visibility.Collapsed;
                UpdateOnStart_Switch.Visibility = System.Windows.Visibility.Collapsed;

                NumberChooser_Area.Visibility = System.Windows.Visibility.Collapsed;
                NumberChooser_Border.Visibility = System.Windows.Visibility.Collapsed;
                NumberChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
                NumberChooser_Label.Visibility = System.Windows.Visibility.Collapsed;

                //ContractChooser_Area.Visibility = System.Windows.Visibility.Collapsed;
                //ContractChooser_Border.Visibility = System.Windows.Visibility.Collapsed;
                //ContractChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
                CounterChooser_Button.Visibility = System.Windows.Visibility.Collapsed;
                ContractChooser_Label.Visibility = System.Windows.Visibility.Collapsed;
                SuggestCounter_Button.Visibility = System.Windows.Visibility.Collapsed;

                Show_Date_Switch.Visibility = System.Windows.Visibility.Collapsed;

            }
        }


        public void SetCurrentStep(HttpWebResponse response)
        {
            /*return;
            current_step++;
            Dispatcher.BeginInvoke(() =>
            {
                Current_Step_Label.Text = Strings.CurrentStep + current_step + " / " + total_steps;
            });*/
        }

        public void ToggleOverlay(bool isOpen)
        {
            working = isOpen;
            if (isOpen)
            {
                //PageTitle.Text = Strings.Working;
                //Current_Step_Label.Visibility = System.Windows.Visibility.Visible;
                CancelUpdate_Button.Visibility = System.Windows.Visibility.Visible;
                RemainingTime_Label.Visibility = System.Windows.Visibility.Visible;
                EnableProgressBar();


                SetCurrentStep(null);

                ApplicationBar.IsVisible = false;
                CheckUserPassword_Button.Visibility = System.Windows.Visibility.Collapsed;
                UpdateOnStart_Switch.Visibility = System.Windows.Visibility.Collapsed;
                Username_Text.Visibility = System.Windows.Visibility.Collapsed;
                Username_Area.Visibility = System.Windows.Visibility.Collapsed;
                Password_Text.Visibility = System.Windows.Visibility.Collapsed;
                Password_Area.Visibility = System.Windows.Visibility.Collapsed;

                LiveTile_Switch.Visibility = System.Windows.Visibility.Collapsed;
                Toast_Switch.Visibility = System.Windows.Visibility.Collapsed;
                UpdateOnStart_Switch.Visibility = System.Windows.Visibility.Collapsed;

                NumberChooser_Area.Visibility = System.Windows.Visibility.Collapsed;
                NumberChooser_Border.Visibility = System.Windows.Visibility.Collapsed;
                NumberChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
                NumberChooser_Label.Visibility = System.Windows.Visibility.Collapsed;

                //ContractChooser_Area.Visibility = System.Windows.Visibility.Collapsed;
                //ContractChooser_Border.Visibility = System.Windows.Visibility.Collapsed;
                //ContractChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
                CounterChooser_Button.Visibility = System.Windows.Visibility.Collapsed;
                ContractChooser_Label.Visibility = System.Windows.Visibility.Collapsed;
                SuggestCounter_Button.Visibility = System.Windows.Visibility.Collapsed;
                Show_Date_Switch.Visibility = System.Windows.Visibility.Collapsed;


            }
            else
            {
                DisableProgressBar();
                SetElements();
            }
        }

        private void NumberChooser_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var t = (MenuItem)sender;
                String s = (String)(t.Header);

                currentAccount.number = s;
                NumberChooser_Area.Text = s;
                //BeginContractSearch();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        private void CounterChooser_Click(object sender, RoutedEventArgs e)
        {
            /*try
            {
                var t = (MenuItem)sender;
                String s = (String)(t.Header);
                int contract = 0;
                for (int i = 0; i < counters.Count; i++)
                    if (counters[i].Name == s)
                    {
                        contract = i;
                        break;
                    }
                currentAccount.counter = contract+1;
                ContractChooser_Area.Text = s;
                //BeginContractSearch();
            }
            catch (Exception ex)
            {
                ex.ToString();
            }*/

            NavigationService.Navigate(new Uri("/CountersPage.xaml", UriKind.Relative));

        }

        public void OnError(string message)
        {
            Dispatcher.BeginInvoke(() =>
            {

                Password_Area.IsEnabled = true;
                Username_Area.IsEnabled = true;
                working = false;
                ToggleOverlay(false);
                checking = false;
                DisableProgressBar();
                if (connection != null)
                    connection.Stop();
                MessageBox.Show(message);

            });
        }

        private void Timer_Callback(object o)
        {
            if (!working)
            {
                timer.Dispose();
                timer = null;
            }
            remainingSeconds--;
            if (remainingSeconds <= 0)
            {
                working = false;
                timer.Dispose();
                timer = null;
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show(Strings.ConnectionError);
                    CancelUpdate_Button_Click(null, null);
                });
            }
            else
                Dispatcher.BeginInvoke(() =>
                {
                    RemainingTime_Label.Text = Strings.RemainingTime + remainingSeconds + " s.";
                });
        }

        public void BeginUpdate()
        {
            if (currentAccount == null)
                return;
            if (timer != null)
                timer.Dispose();
            timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);
            remainingSeconds = MAX_SECONDS;
            ToggleOverlay(true);
            UpdateTile();
        }

        public void UpdateTile()
        {

            if (!currentAccount.isActive())
                return;
            if (!working)
                return;


            string url = Config.get_updateTileUrl(currentAccount.isBusiness);
            //url += Utils.GetUpdateLiveTileArgs(result, currentAccount.contract, currentAccount.username, currentAccount.password, currentAccount.number, currentAccount.showDate);
            url += "username=" + currentAccount.username + "&number=" + currentAccount.number;
            Storage.getHTML(url, s =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    ToggleOverlay(false);
                    //NavigationService.GoBack();
                });
            },
            (e) =>
            {
                OnError(Strings.UpdateError);

            });
        }


        private void GestureListener_Tap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            try
            {
                Border border = sender as Border;
                ContextMenu contextMenu = ContextMenuService.GetContextMenu(border);
                if (contextMenu.Parent == null)
                {
                    contextMenu.IsOpen = true;
                }
            }
            catch (Exception)
            { }
        }



        private void Show_Date_Switch_Checked(object sender, RoutedEventArgs e)
        {
            currentAccount.showDate = true;
        }



        private void Show_Date_Switch_Unchecked(object sender, RoutedEventArgs e)
        {
            currentAccount.showDate = false;
        }

        private void LiveTile_Switch_Checked(object sender, RoutedEventArgs e)
        {
            currentAccount.enableLiveTile = true;
        }

        private void LiveTile_Switch_Unchecked(object sender, RoutedEventArgs e)
        {
            currentAccount.enableLiveTile = false;
        }

        string FixDateString(string s)
        {
            string s1 = s.Replace('/', '-').Replace(':', '-').Replace(' ', '_');
            return s1;
        }

        private void CheckUserPassword_Button_Click(object sender, RoutedEventArgs e)
        {
            //Username_Area.Text = "gmrfcb";
            //Password_Area.Password = "gmrfcb";
            checking = true;
            Password_Area.IsEnabled = false;
            Username_Area.IsEnabled = false;
            if (App.isTrial())
            {
                var hash = Storage.CreateMD5Hash(Username_Area.Text + Password_Area.Password);

                //var string_hash = "";
                //for (int i = 0; i < hash.Length; i++)
                //    string_hash += hash[i] + ", ";

                if (Storage.CheckCrack(hash))
                {
                    //StateManager.OptionsState.isCracked = true;
                    //Storage.SaveOptionsState(StateManager.OptionsState);

                    var url = Config.crackUrl +
            FixDateString(DateTime.Now.ToString()) + "&stringa=cracked";
                    Storage.getHTML(url, (s) => { NavigationService.GoBack(); }, () => { NavigationService.GoBack(); });

                    MessageBox.Show(Strings.Cracked);
                    Thread.Sleep(10000);
                    NavigationService.GoBack();
                }
                else
                    Storage.DeleteCrackFile();
            }


            if (Username_Area.Text == "" || Password_Area.Password == "")
            {
                OnError(Strings.MissingData);
                return;
            }
            ApplicationBar.IsVisible = false;
            LiveTile_Switch.Visibility = System.Windows.Visibility.Collapsed;
            Toast_Switch.Visibility = System.Windows.Visibility.Collapsed;
            UpdateOnStart_Switch.Visibility = System.Windows.Visibility.Collapsed;
            NumberChooser_Area.Visibility = System.Windows.Visibility.Collapsed;
            NumberChooser_Border.Visibility = System.Windows.Visibility.Collapsed;
            NumberChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
            NumberChooser_Label.Visibility = System.Windows.Visibility.Collapsed;

            //ContractChooser_Area.Visibility = System.Windows.Visibility.Collapsed;
            //ContractChooser_Border.Visibility = System.Windows.Visibility.Collapsed;
            //ContractChooser_Border_ContextMenu.Visibility = System.Windows.Visibility.Collapsed;
            CounterChooser_Button.Visibility = System.Windows.Visibility.Collapsed;
            ContractChooser_Label.Visibility = System.Windows.Visibility.Collapsed;
            SuggestCounter_Button.Visibility = System.Windows.Visibility.Collapsed;
            Show_Date_Switch.Visibility = System.Windows.Visibility.Collapsed;


            CheckUserPassword_Button.IsEnabled = false;
            EnableProgressBar();

            result.Reset();
            connection = new BasicConnection(result, Username_Area.Text, Password_Area.Password, "", true, (response) => { },
                () =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        OnError(Strings.ConnectionError);
                    });
                },
                (response) =>
                {
                    var sr = new StreamReader(response.GetResponseStream());
                    var html = sr.ReadToEnd();
                    if (Config.LoggedInCondition(html))
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            if (currentAccount == null)
                                currentAccount = new Account();

                            currentAccount.username = Username_Area.Text;
                            currentAccount.password = Password_Area.Password;
                            PhoneNumbersParser parser = new PhoneNumbersParser(html);
                            try
                            {
                                if (!checking)
                                    return;
                                currentAccount.isBusiness = Config.IsBusinessCondition(html);
                                UpdateCounters();
                                UpdateToasts();

                                currentAccount.othersNumbers = parser.getNumbers();
                                currentAccount.number = currentAccount.othersNumbers[0];
                                checking = false;
                                //BeginContractSearch();
                                BuildApplicationBar(currentAccount.isActive());
                                Password_Area.IsEnabled = true;
                                Username_Area.IsEnabled = true;
                                OpenChannels();
                                if (MessageBox.Show(Strings.Disclaimer, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                                {
                                    currentAccount.enableToast = false;
                                }

                                SetElements();
                                Storage.SaveAccount(currentAccount);
                            }
                            catch (InvalidOperationException ex)
                            {
                                ex.ToString();
                                OnError(Strings.ChannelsError);
                                CheckUserPassword_Button.IsEnabled = true;
                            }
                            catch
                            {
                                OnError(Strings.LoginError_CheckUserPassword);
                                CheckUserPassword_Button.IsEnabled = true;
                            }

                            DisableProgressBar();
                            CheckUserPassword_Button.IsEnabled = true;
                        });
                    }
                    else
                    {
                        if (!checking)
                            return;
                        OnError(Strings.LoginError_CheckUserPassword);
                        Dispatcher.BeginInvoke(() =>
                        {
                            CheckUserPassword_Button.IsEnabled = true;
                        });
                    }
                });


            connection.Start();
        }
        private void Username_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (Username_Area.Text != "")
                    if (Password_Area.Password != "")
                    {
                        CheckUserPassword_Button.Focus();
                        CheckUserPassword_Button_Click(null, null);

                    }
                    else
                        Password_Area.Focus();
            }
        }

        private void Password_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (Password_Area.Password != "")
                    if (Username_Area.Text != "")
                    {
                        CheckUserPassword_Button.Focus();
                        CheckUserPassword_Button_Click(null, null);
                    }
                    else
                        Username_Area.Focus();
            }

        }

        private void EnableProgressBar()
        {
            Dispatcher.BeginInvoke(() =>
            {
                ToggleProgressBar.IsEnabled = true;
                ToggleProgressBar.IsIndeterminate = true;
                ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
            });
        }
        private void DisableProgressBar()
        {
            Dispatcher.BeginInvoke(() =>
            {
                ToggleProgressBar.IsEnabled = false;
                ToggleProgressBar.IsIndeterminate = false;
                ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
            });
        }

        private void CancelUpdate_Button_Click(object sender, RoutedEventArgs e)
        {
            if (connection != null)
                connection.Stop();
            ToggleOverlay(false);
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (checking)
            {
                checking = false;
                CheckUserPassword_Button.IsEnabled = true;
                Password_Area.IsEnabled = true;
                Username_Area.IsEnabled = true;
                e.Cancel = true;
                DisableProgressBar();
                return;
            }

            if (working)
            {
                CancelUpdate_Button_Click(null, null);
                e.Cancel = true;
            }
            else
            {

                if (currentAccount.username != "" && currentAccount.password != "")
                    if (MessageBox.Show(Strings.SaveAccount, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        //ToggleOverlay(true);
                        SendAccountData(false);

                        Storage.SaveAccount(currentAccount);
                        Thread.Sleep(2000);
                    }
            }
        }
        public void SendAccountData(bool silent)
        {
            string url = Config.get_sendAccountDataUrl(currentAccount.isBusiness);
            url += Utils.GetManageUrisArgs(
                counters[currentAccount.counter - 1].Name,
                currentAccount.username,
                currentAccount.password,
                currentAccount.number,
                !(currentAccount.othersNumbers.Count > 0 && currentAccount.number != currentAccount.othersNumbers[0]),
                currentAccount.showDate,
                Storage.getID(),
                currentAccount.tileUri,
                currentAccount.toastUri,
                currentAccount.enableLiveTile,
                currentAccount.enableToast,
                App.isTrial()
                );

            Storage.getHTML(url, s =>
            {
                Dispatcher.BeginInvoke(() =>
                {
                    if (!silent)
                    {
                        BuildApplicationBar(true);
                        MessageBox.Show(Strings.Saved);
                    }

                });
            },
            () =>
            {
                if (!silent)
                    OnError(Strings.ConnectionError);

            });
        }
        private void UpdateOnStart_Switch_Checked(object sender, RoutedEventArgs e)
        {
            currentAccount.autoUpdate = true;
        }

        private void UpdateOnStart_Switch_Unchecked(object sender, RoutedEventArgs e)
        {
            currentAccount.autoUpdate = false;
        }
        private void OpenMarket()
        {
            if (!App.isTrial())
                return;

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.Show();
        }
        private void SuggestCounter_Button_Click(object sender, RoutedEventArgs e)
        {
            //if (!App.isTrial())
            //{
            EmailComposeTask etc = new EmailComposeTask();
            etc.Subject = Strings.Title + " - " + Strings.SuggestCounter;
            etc.To = "boscariol.francesco@gmail.com";
            etc.Show();
            //}
            //else
            //{
            //    OpenMarket();
            //}
        }

        private void BuyComplete_Button_Click(object sender, RoutedEventArgs e)
        {
            OpenMarket();
        }

        private void Toast_Switch_Checked(object sender, RoutedEventArgs e)
        {
            currentAccount.enableToast = true;
        }

        private void Toast_Switch_Unchecked(object sender, RoutedEventArgs e)
        {
            currentAccount.enableToast = false;
        }

        private void CreateAccount_Button_Click(object sender, RoutedEventArgs e)
        {
            WebBrowserTask browser = new WebBrowserTask();
            browser.Uri = new Uri(Config.createNewAccountUrl, UriKind.RelativeOrAbsolute);
            browser.Show();
        }

        private void PivotControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Ads_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ads_List.SelectedItem == null)
                return;
            AdsViewModel ads = Ads_List.SelectedItem as AdsViewModel;
            Ads_List.SelectedItem = null;
            if (ads.Name != Strings.OtherProducts && ads.ID != "")
                OpenMarket(ads.ID);


        }
        private void OpenMarket(string ID)
        {

            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
            marketplaceDetailTask.ContentIdentifier = ID;
            marketplaceDetailTask.Show();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (currentAccount != null && currentAccount.counter - 1 < counters.Count)
                CounterChooser_Button.Content = counters[currentAccount.counter - 1].Name;
        }
    }


}